package com.lychee.socketservice;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    private TextView mTvContent, mTvIp;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                mTvContent.setText("client：" + msg.obj + "\n");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvContent = findViewById(R.id.mTvContent);
        mTvIp = findViewById(R.id.mTvIP);
        String clientIP = getClientIP();
        mTvIp.setText(clientIP);
        new Thread(new ConnectClient(), "服务端连接线程").start();
    }

    private class ConnectClient implements Runnable {

        @Override
        public void run() {

            OutputStream output;
            String serverContent = "hello 我是Service端发送过来的数据";
            try {
                ServerSocket serverSocket = new ServerSocket(30000);
                while (true) {
                    Message msg = new Message();
                    msg.what = 1;
                    try {
                        Socket socket = serverSocket.accept();
                        //向client发送消息
                        System.out.println("客户端IP"+socket.getInetAddress());
                        output = socket.getOutputStream();
                        output.write(serverContent.getBytes("utf-8"));
                        output.flush();
                        socket.shutdownOutput();

                        //获取输入信息
                        BufferedReader bff = new BufferedReader(new InputStreamReader
                                (socket.getInputStream()));
                        //读取信息
                        String result = "";
                        String buffer;
                        while ((buffer = bff.readLine()) != null) {
                            result = result + buffer;
                        }
                        msg.obj = result.toString();
                        mHandler.sendMessage(msg);
                        bff.close();
                        output.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
    }

    /**
     * 获取客户端IP
     *
     * @return
     */
    private String getClientIP() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        int ipAddress = connectionInfo.getIpAddress();
        System.out.println(ipAddress);
        if (ipAddress == 0) {
            return "";
        }
        return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

    }


}
